<?php
/*
 * Auther Bachue
 * As the name of this file, if you run it, it will read your AuthzSvnAccessFile
 * and copy info to your database
 */

include_once './config/config.php';
include_once './config/dbconf.php';

global $config;
global $dbconf;

$reponame='';
$path='';

$connect=getPdoConnection();
if(!$connect)
{
    echo 'Database can\'t connect';
    //TODO log
    exit;
}

$file=fopen($config['AuthzSvnAccessFilePath'],'r');
if(!$file)
{
    echo "File System Error";
    //TODO log
    exit;
}
if(flock($file, LOCK_SH)===false)
{
    echo 'File System Busy';
    //TODO log
    exit;
}

if($connect->exec("truncate table `{$dbconf['groups_tablename']}`")===false)
{
    echo 'Database Error';
    //TODO log
    exit;
}
if($connect->exec("truncate table `{$dbconf['privileges_tablename']}`")===false)
{
    echo 'Database Error';
    //TODO log
    exit;
}

$insert_into_groups=$connect->prepare("insert into `{$dbconf['groups_tablename']}` values(:groupname,:username)");
$insert_into_privileges=$connect->prepare("insert into `{$dbconf['privileges_tablename']}` values(:reponame,:path,:privilege,:name)");

while($line=fgets($file))
{
    $line=trim($line);
    if(empty($line)) continue;
    else if(preg_match("/^\[/", $line)) //to parse tag likes [repo1:/]
    {
        $array=explode(':',trim($line,'[]')); //to convert [repo1:/] to repo1 and /
        if(!empty($array[1]))
        {
            $reponame=trim($array[0]);
            $path=trim($array[1]);
        }
        else //may be the line likes [/] or [groups]
        {
            $reponame="";
            $path=trim($array[0]);
        }
    }
    else if($path==='groups' && empty($reponame)) // if the tag likes [groups], we will set $groups_list
    {
        $array=explode('=', $line);
        $groupname=rtrim($array[0]);
        $userlist=ltrim($array[1]);
        /*if the userlist likes bachue,hikui,liuxiaobo, we will split the string to three people  */
        $userlist=explode(',', $userlist);
        foreach($userlist as $user)
        {
            if($insert_into_groups->execute(
                    array(':groupname'=>$groupname,':username'=>trim($user)))===false)
            {
                echo 'Database Error';
                //TODO log
                exit;
            }
        }
    }
    else //set $privileges_list
    {
        $array=explode('=', $line);
        $userlist=rtrim($array[0]);
        $privilegelists=ltrim($array[1]);
        if($insert_into_privileges->execute(
                array(':reponame'=>$reponame,':path'=>$path,':privilege'=>$privilegelists,':name'=>$userlist))===false)
        {
            echo 'Database Error';
            //TODO log
            exit;
        }
    }
}

$connect=null;
flock($file, LOCK_UN);
fclose($file);
echo 'Database Updated Successfully';

?>
